package com.module.app.utils

import com.module.ad_gromore.AdGromoreInit
import com.alibaba.android.arouter.launcher.ARouter
import com.module.app.base.BaseApplication
import com.module.app.widget.dialog.LoadingDialogImpl
import com.module.base.arouter.BaseArouterUtils
import com.module.base.utils.*
import com.kingja.loadsir.core.LoadSir
import com.module.app.base.loadsir.*
import com.module.base.BuildConfig
import com.module.base.R
import com.module.frame.dialog.LoadingDialogUtils
import com.module.skin.SkinUtils
import com.module.third.BmobUtils
import com.module.third.UMUtils
import com.module.third.learcloud.initLCPush
import com.module.third.learcloud.initLearnCloud
import com.module.third.qiniu.QiniuConfig
import com.module.third.qiniu.QiniuSignUtils
import com.module.third.wx.WxConfig
import io.reactivex.plugins.RxJavaPlugins
import java.io.File

/**
 * @author bsnl_yanxuwen
 * @date 2021/1/22 16:53
 * Description :
 * 全局初始化，不建议放在BaseApplication
 */
open class InitializationUtils {
    companion object {
        private var isInit = false
        var isInitSDK = false
        var umId = "60a9e837c9aacd3bd4e2d415"
        var bmobId = "52cb3031501b68260696c575bf03d8c8"
        var lcAction = "com.aiyu.privacy.data"
        var lcAppId = "OyYlvO13APqSQxDH4I140yqK-gzGzoHsz"
        var lcAppKey = "CJ6XrmCu4mGL5kRTjPwcPbxt"
        var lcServerUrl = "https://oyylvo13.lc-cn-n1-shared.com"
        var WX_APP_ID = "wxfe9e1e191bd421c2"

        /**
         * 初始化第三方
         */
        @Synchronized
        fun init() {
            if (isInit) {
                return
            }
            isInit = true
            initLoadSir()
            initARouter()
            initLoadDialog()
            initRetrofit()
            //RxJava OnErrorNotImplementedException 的处理
            RxJavaPlugins.setErrorHandler {
                //异常处理
            }
            //微信
            WxConfig.WX_APP_ID = WX_APP_ID
        }

        /**
         * 初始化第三方SDK(必须启动的时候，点击同意才能调用)
         */
        @Synchronized
        fun initSDK() {
            if (isInitSDK) {
                return
            }
            isInitSDK = true
            delTemporaryPath()
            initShare()
            initSkin()
            initAD()
            initBmob()
            initLeanCloud()
            initLearnCloudPush()
            initUM()
            initQiniu()
        }

        /**
         * 数据初始化，常用于一些工具类，避免什么东西都放在WelcomeActivity
         */
        fun initData() {
            //引导评价
            EvaluateUtils.startUp()
            //检查皮肤
            MySkinUtils.checkSkin()
            //检查系统是否是夜间模式
            AutoSkinNightUtils.followSystem()
        }

        /**
         * onResume 数据初始化
         * 频繁触发，慎重使用
         */
        fun onResume() {}
        private fun initARouter() {
            if (BuildConfig.DEBUG) {
                ARouter.openLog() // 打印日志
                ARouter.openDebug() // 开启
            }
            ARouter.init(BaseApplication.getInstance())
        }

        private fun initLoadSir() {
            LoadSir.beginBuilder()
                .addCallback(ErrorCallback())
                .addCallback(EmptyCallback())
                .addCallback(LoadingCallback())
                .setDefaultCallback(LoadingCallback::class.java) //设置默认状态页
                .commit()
        }

        /**
         * 初始化弹窗相关
         */
        private fun initLoadDialog() {
            LoadingDialogUtils.setDialogImpl(com.module.app.widget.dialog.LoadingDialogImpl::class.java)
        }

        private fun initRetrofit() {
            com.module.app.network.initRetrofit("https://bxapi.bisinuolan.cn/")
        }

        /**
         * 删除临时目录
         */
        private fun delTemporaryPath() {
            ThreadPoolManager.getInstance().execute {
                val filePath = FileUtils.getTemporaryPath()
                FileCommonUtils.deleteFolder(filePath)
                //刷新库
                val fileName = FileUtils.getSDAppPath()
                val file = File(fileName)
                try {
                    SingleMediaScanner(
                        BaseApplication.getContext(), file
                    ) { }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
                LogUtils.d("删除临时文件夹")
            }
        }

        private fun initBmob() {
            BmobUtils.init(BaseApplication.getContext(), bmobId)
        }

        private fun initLeanCloud() {
            val myAction = lcAction
            val appId = lcAppId
            val appKey = lcAppKey
            val serverUrl = lcServerUrl
            initLearnCloud(myAction, appId, appKey, serverUrl)
        }

        /**
         * LearnCloud 推送初始化
         */
        fun initLearnCloudPush() {
            val service = BaseArouterUtils.getBaseService() ?: return
            val mClass = service.defaultPushActivity
            initLCPush(BaseApplication.getContext(), mClass, AppUtils.getChannel())
        }

        /**
         * 广告初始化
         */
        private fun initAD() {
//        AdInit.init(BaseApplication.getContext(), ConfigBean.getInstance().getAd().getTTId(), ConfigBean.getInstance().getAd().getTxId());
            AdGromoreInit.init(
                BaseApplication.getContext(),
                "5166727",
                CommonUtils.getString(R.string.app_name)
            )
        }

        /**
         * 友盟初始化
         */
        private fun initUM() {
            //debug版本，友盟不记录
            if (!BuildConfig.DEBUG) {
                UMUtils.init(BaseApplication.getContext(), umId, AppUtils.getChannel())
            }
        }

        /**
         * 分享初始化
         */
        private fun initShare() {
            //分享注册类型,注册了才能使用类型代替.class类，如果不注册，可以使用.class传递也可以
//            ShareConfigure.Register()
//                .addLayutType(ShareLayoutType.TYPE_NORMAL, NormalLayoutType::class.java) //添加普通分享
//                .addLayutType(
//                    ShareLayoutType.TYPE_DEFAULT,
//                    DefaultLayoutType::class.java
//                ) //添加布局类型-默认
//                .commit()
//            //分享初始化默认配置
//            ShareConfigure.Builder()
//                .setLayoutType(ShareLayoutType.TYPE_DEFAULT)
//                .setSavePath(FileUtils.getSDAppPath())
//                .setViewPage(true)
//                .setCardScale(0.92f)
//                .commit()
        }

        /**
         * 皮肤初始化
         */
        private fun initSkin() {
            SkinUtils.init(
                BaseApplication.getInstance(),
                FileUtils.getSkinPath(),
                windowBg = true,
                statusBg = false
            )
        }

        /**
         * 七牛云初始化
         */
        private fun initQiniu() {
            val config = QiniuConfig()
            config.apply {
                access_key = "CMG3DH-Oft9IbfdY4oCrUZn_0ZQG-OOSY6yD00bA"
                secret_key = "2snTWfSjf4Sl-rJYvxdhMkQJpuTpEWgZF_yfRZAa"
                bucket = "privates-club"
                host = "aiyuxm.com"
                listener = QiniuConfig.Listener { _, _, _ -> null }
            }
            QiniuSignUtils.init(config)
        }
    }
}